import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import { getShopList, getTypeList } from "../api/http"

//存放所有的数据
let initialState = {
    shoplist: [],//商品列表数据
    typelist: [],//商品分类数据
    activeKey: '1'//下标
}


const todosSlice = createSlice({
    name: "todos",
    initialState,
    reducers: { //同步方法

        //获取商品列表数据
        getshoplist(state, action) {
            state.shoplist = action.payload
        },
        //获取商品分类数据
        gettypelist(state, action) {
            state.typelist = action.payload
        },
        //商品列表添加的方法
        addshoplist(state, action) {
            state.shoplist.push(action.payload)
        },
        //商品列表编辑的方法
        updateshoplist(state, action) {
            let i = state.shoplist.findIndex(item => {
                return item.id == action.payload.id
            })
            state.shoplist[i] = action.payload
        },
        //商品列表删除方法
        delshoplist(state, action) {
            state.shoplist = state.shoplist.filter(item => {
                return item.id !== action.payload
            })
        },
        //商品分类高亮
        changeactiveKey(state, action) {
            state.activeKey = action.payload
        },
        //商品分类添加的方法
        addtypelist(state, action) {
            state.typelist.push(action.payload)
        },
        //商品列表删除方法
        deltypelist(state, action) {
            
            state.typelist = state.typelist.filter(item => {
                return item.key !== action.payload
            })
        },


    },
});

export const {
    getshoplist, gettypelist, addshoplist, updateshoplist, delshoplist,
    changeactiveKey, addtypelist, deltypelist
} = todosSlice.actions;
export default todosSlice.reducer;

//异步方法 商品列表
export let async_shoplist = createAsyncThunk('async_shoplist',
    async (_, store) => {
        //获取异步方法
        let res = await getShopList()
        //console.log(res);
        //同步修改异步
        store.dispatch(getshoplist(res))
    })

//分类列表
export let async_typelist = createAsyncThunk('async_typelist',
    async (_, store) => {
        //获取异步
        let res = await getTypeList()
        //console.log(res);
        //同步修改异步
        store.dispatch(gettypelist(res))
    })
